/**
 * Created by mybbcat on 2015/12/10.
 * 账号相关的逻辑服务
 */


  define(['app','crypto',"underscore"],function (app,CryptoJS,_) {
  app.factory('accountService', ['globalConfig', '$http', '$q', function (globalConfig, $http, $q) {
    var serviceFactory = {};

    serviceFactory.smsCode = _getSmsCode;
    serviceFactory.signinCompany = _postSignInCompany;
    serviceFactory.signUp = _signUp;
    serviceFactory.getCompanySimpleInfor = _getCompanySimpleInfor;
    serviceFactory.exitMember = _exitMember;

    /**
     * 请求向手机发送一个短信验证码
     * @param phoneNo 手机号码
     * @param securityCode 安全验证码
     * @private
     */
    function _getSmsCode(phoneNo, securityCode) {
      var deferred = $q.defer();

      var url = globalConfig.apiUrl.account.getSmsSecurityCode.format(phoneNo, securityCode);

      $http.get(url).success(function (response) {
        deferred.resolve(response);
      }).error(function (err) {
        deferred.reject(err)
      });
      return deferred.promise;
    }

    /**
     * 注册企业账号
     * @param data addCompanyVm
     * @returns {*}
     * @private
     */
    function _postSignInCompany(data) {
      var deferred = $q.defer();

      var url = globalConfig.apiUrl.account.registerCompany;

      $http.post(url, data).success(function (response) {
        deferred.resolve(response);
      }).error(function (err) {
        deferred.reject(err)
      });
      return deferred.promise;
    }


    /*注册成员*/
    function _signUp(data) {
      //todo 注册
      var deferred = $q.defer();
      var url = globalConfig.apiUrl.account.registerMember.format(data.companyId);
      $http.post(url, data).success(function (response) {
        deferred.resolve(response);
      }).error(function (err) {
        deferred.reject(err)
      });
      return deferred.promise;
    }

    /**
     *获取公司信息
     * @param companyId 公司id
     **/
    function _getCompanySimpleInfor(companyId) {
      var deferred = $q.defer();
      console.info(globalConfig.apiUrl.company.getCompanySimpleInfor);
      var url = globalConfig.apiUrl.company.getCompanySimpleInfor.format(companyId);
      $http.get(url).success(function (response) {
        deferred.resolve(response);
      }).error(function (err) {
        deferred.reject(err)
      });
      return deferred.promise;
    }

    /**
     *修改成员信息
     * @param companyId 公司id
     **/
    function _exitMember(data) {
      var deferred = $q.defer();
      var url = globalConfig.apiUrl.account.exitMember.format(data.CompanyId, data.MemberId);
      $http.put(url, data).success(function (response) {
        deferred.resolve(response);
      }).error(function (err) {
        deferred.reject(err)
      });
      return deferred.promise;
    }


    return serviceFactory;
  }]);

/**
 * Created by jianbo on 2016/3/25.
 */

  app.factory('authService', ['globalConfig', '$http', '$q', '$window', '$state', function (globalConfig, $http, $q, $window, $state) {

    var authServiceFactory = {};

    var _authentication = {
      isAuth: false,
      userName: ''
    };

    authServiceFactory.signIn = _signIn;
    authServiceFactory.signOut = _signOut;
    authServiceFactory.fillAuthData = _fillAuthData;
    authServiceFactory.authentication = _authentication;

    /*进行登录*/
    function _signIn(username, password) {
      var deferred = $q.defer();
      $http.post(globalConfig.apiUrl.token, {account: username, password: password})
        .success(function (response) {
          var _data = {token: response.token, userName: username};
          $window.sessionStorage.setItem('authorizationData', JSON.stringify(_data));

          _authentication.isAuth = true;
          _authentication.userName = username;

          deferred.resolve(response);
        }).error(function (err, status) {
        _signOut();
        deferred.reject(err)
      });
      return deferred.promise;
    }

    /*退出登录*/
    function _signOut() {
      $window.sessionStorage.removeItem('authorizationData');
      _authentication.isAuth = false;
      _authentication.userName = '';

      $state.go('access.signin');
    }

    //初始化APP时，或刷新APP时，重新去本地session中获取认证数据，检查是否已经通过认证
    function _fillAuthData() {
      var authData = $window.sessionStorage.getItem('authorizationData');
      if (authData) {
        _authentication.isAuth = true;
        _authentication.userName = authData.userName;
      }
    }

    return authServiceFactory;
  }]);
/**
 * Created by jianbo on 2016/3/25.
 */

  app.factory('currentUserService', ['globalConfig', '$http', 'CacheFactory', '$q', function (globalConfig, $http, CacheFactory, $q) {
    //这里利用第三方的缓存插件
    CacheFactory('dataCache', {
      maxAge: 15 * 60 * 1000, // Items added to this cache expire after 15 minutes
      cacheFlushInterval: 60 * 60 * 1000, // This cache will clear itself every hour
      deleteOnExpire: 'aggressive' // Items will be deleted from this cache when they expire
    });
    var serviceFactory = {};
    var _currentUser = {
      id: '',
      company: {
        id: '',
        name: ''
      },
      name: '',
      phone: '',

      departmentList: {
        name: ''
      },
      roleList: {
        name: ''
      },
      firstlogin: '',
      functionPermission: {}
    };

    serviceFactory.currentUser = _getCurrentUser;

    function _getCurrentUser() {
      var deferred = $q.defer();
      var url = globalConfig.apiUrl.account.getMyInfo;
      var start = new Date().getTime();
      $http.get(url, {
        cache: CacheFactory.get('dataCache')
      }).success(
        function (data) {
          console.log('time taken for request: ' + (new Date().getTime() - start) + 'ms');
          _success(data, deferred);
        }, function () {
          _error(deferred);
        });
      return deferred.promise;
    }

    function _success(response, deferred) {
      _currentUser.id = response.memberinfo.id;
      _currentUser.company.id = response.memberinfo.companyId;
      _currentUser.name = response.memberinfo.name;
      _currentUser.phone = response.memberinfo.tel1;
      _currentUser.departmentList = response.memberinfo.departmentList;
      _currentUser.roleList = response.memberinfo.roleList;
      _currentUser.firstlogin = response.firstlogin;
      deferred.resolve(_currentUser);
    }

    function _error(deferred) {
      deferred.reject(_currentUser);
    }

    return serviceFactory;
  }]);

/**
 * Created by jianbo on 2016/3/25.
 */

  app.factory('tokenInterceptorService', ['$q', '$window', '$injector', "globalConfig", function ($q, $window, $injector, globalConfig) {
    return {
      /*
       修改请求正文
       */
      request: function (config) {
        config.headers = config.headers || {};

//在请求中附带认证令牌
        var authData = $window.sessionStorage.getItem('authorizationData');
        if (authData) {
          var _data = JSON.parse(authData);
          config.headers.token = _data.token;
        }

//todo 加载中全局提示

        return config;
      },

      requestError: function (config) {

//todo 取消加载中全局提示
        return $q.reject(config);
      },

      /*
       获得响应对象，可以修改它
       */
      response: function (response) {

//TODO 停止加载中全局提示

        return response || $q.when(response);
      },

      /* Revoke client authentication if 401 is received */
      responseError: function (response) {
        if (response != null) {
        }
        switch (response.status) {
          case 401:
            $injector.get('$state').transitionTo('access.signin');
            break;
          case -1:
            //TODO 使用弹出提示框进行提示
            console.warn("无法连接服务器！");
            break;
          case 405:
            //TODO 使用弹提示框进行提示
            console.warn("服务器拒绝访问！");
            break;
          case 400 || 500:
            console.warn(response.data.message.join(';'));
            break;
          default :
            console.error("404");
            break;
        }
//todo 取消加载中全局提示
        return $q.reject(response);
      }
    };
  }]);

/**
 * Created by jianbo on 2016/3/25.
 */

  app.factory('cryptoJS', function () {
    return CryptoJS;
  });

  app.factory('underscoreJS', function () {
    return _;
  });
});
